package com.cop4331.social;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 
 * @author Matt Szoke
 * @LastUpdated: 4/12/2012 by Matt Szoke
 * 
 * List of Pending Tutor Requests
 * 
 */
public class TutorPending extends Activity {

	public static String term;
	public static String un;
	ListView pending;
	EditText duser;
	EditText ddate;
	EditText dtime;
	EditText dsubject;
	EditText dother;
	EditText dloc;
	TextView nopending;
	TextView tv_tutor;
	Button confirm;
	Button decline;
	Button reschedule;
	Button cancel;
	Button profile;

	// -----------------------------------------------
	// ONCREATE
	// -----------------------------------------------
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		// XML associated with TutorPending: tutorpending.xml
		setContentView(R.layout.tutorpending);

		pending = (ListView) findViewById(R.id.pendingList);
		nopending = (TextView) findViewById(R.id.notutors);

		// Retreive current term from SQLite Database
		DatabaseHandler db = new DatabaseHandler(getApplicationContext());
		HashMap<String, String> user = db.getUserDetails();
		term = user.get("uid");
		un = user.get("name");

		Parcelable state = pending.onSaveInstanceState();

		// Assign adapter to ListView
		try {

			// Set adapter
			// Adapter comes from SimpleAdapter_Ext Class

			List<Map<String, Object>> data = getData();

			if (data.size() != 0)
				nopending.setVisibility(View.GONE);

			pending.setAdapter(new SpecialAdapter(this, getData(),
					R.layout.tutorpendinglist, new String[] { "sub", "date",
							"time", "tutoree", "tutor", "other" }, new int[] {
							R.id.course, R.id.date, R.id.time }));

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		pending.onRestoreInstanceState(state);

		// Give the listview functionality when a user clicks it
		pending.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int pos,
					long id) {

				// Retreive the current selected item details
				final Map<String, Object> item = (Map<String, Object>) parent
						.getItemAtPosition(pos);

				Dialog dialog = new Dialog(TutorPending.this);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.tutorpendingdialog);
				dialog.setCancelable(true);

				duser = (EditText) dialog.findViewById(R.id.duser);
				ddate = (EditText) dialog.findViewById(R.id.ddate);
				dtime = (EditText) dialog.findViewById(R.id.dtime);
				dsubject = (EditText) dialog.findViewById(R.id.dsub);
				dother = (EditText) dialog.findViewById(R.id.dother);
				confirm = (Button) dialog.findViewById(R.id.b_confirm);
				decline = (Button) dialog.findViewById(R.id.b_decline);
				reschedule = (Button) dialog.findViewById(R.id.b_reschedule);
				cancel = (Button) dialog.findViewById(R.id.b_cancel);
				profile = (Button) dialog.findViewById(R.id.b_profile);
				tv_tutor = (TextView) dialog.findViewById(R.id.tv_tutor);
				dloc = (EditText) dialog.findViewById(R.id.dloc);

				final String userProfile;
				
				// Decline Tutor session request
				cancel.setVisibility(View.GONE);

				if (item.get("tutoree").toString().compareTo(un) == 0) {

					if (item.get("type").toString().compareTo("3") != 0) {
						confirm.setVisibility(View.VISIBLE);
					} else
						confirm.setVisibility(View.GONE);

					duser.setText(item.get("tutor").toString());
					tv_tutor.setText("Requested Tutor");
					userProfile = item.get("tutor").toString();
				} else {
					if (item.get("type").toString().compareTo("4") != 0) {
						confirm.setVisibility(View.VISIBLE);
					} else
						confirm.setVisibility(View.GONE);

					duser.setText(item.get("tutoree").toString());
					userProfile = item.get("tutoree").toString();
				}
				
				// Set session information in the dialog
				ddate.setText(item.get("date").toString());
				dtime.setText(item.get("time").toString());
				dsubject.setText(item.get("sub").toString());
				dother.setText(item.get("other").toString());
				dloc.setText(item.get("location").toString());
				
				// Confirm this session
				confirm.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						
						// Update database
						UserFunctions uf = new UserFunctions();
						uf.updateSession(item.get("id").toString(), "2");
						
						// Send confirmation message to user
						uf.addMessage(
								"CramSessions",
								duser.getText().toString(),
								"Tutor Request",
								un
										+ " has accepted a tutoring session with you.  Check your notifications for more details.");

						Intent log = new Intent(getApplicationContext(),
								TutorNotifications.class);
						startActivity(log);
					}
				});
				
				// Remove this session from the database on decline
				decline.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						UserFunctions uf = new UserFunctions();
						uf.deleteSession(item.get("id").toString());

						Intent log = new Intent(getApplicationContext(),
								TutorNotifications.class);
						startActivity(log);
						finish();

					}
				});
				
				// Reschedule this session with the request user
				reschedule.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {

						// Bundle the selected tutor for the
						// ScheduleRequestActivity (We will add to the database
						// in the next frame)
						Bundle b = new Bundle();
						b.putString("tutor", item.get("tutor").toString());
						b.putString("cname", item.get("sub").toString());
						b.putString("tutoree", item.get("tutoree").toString());
						b.putString("id", item.get("id").toString());

						if (item.get("tutor").toString().compareTo(un) == 0) {
							b.putString("type", "4");
						} else {
							b.putString("type", "3");
						}

						// Goto the ScheduleRequestActivity
						Intent log = new Intent(getApplicationContext(),
								RescheduleRequestActivity.class);
						log.putExtras(b);
						startActivity(log);
						finish();
					}
				});

				dialog.setCanceledOnTouchOutside(true);
				dialog.show();
				
				// Show profile dialog
				profile.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {

						UserFunctions uf = new UserFunctions();

						try {

							final Dialog dialog1 = new Dialog(TutorPending.this);
							dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
							dialog1.setContentView(R.layout.viewprofiledialog);
							dialog1.setCancelable(true);

							JSONObject json_user = uf.userExists(userProfile)
									.getJSONObject("user");

							final RatingBar rating = (RatingBar) dialog1
									.findViewById(R.id.rating);
							ImageView pic = (ImageView) dialog1
									.findViewById(R.id.profilepic);
							TextView name = (TextView) dialog1
									.findViewById(R.id.name);
							TextView phone = (TextView) dialog1
									.findViewById(R.id.phone);
							TextView email = (TextView) dialog1
									.findViewById(R.id.email);
							TextView major = (TextView) dialog1
									.findViewById(R.id.major);
							TextView cnt = (TextView) dialog1
									.findViewById(R.id.count);
							Button close = (Button) dialog1
									.findViewById(R.id.close);
							Button message = (Button) dialog1
									.findViewById(R.id.message);
							
							// Set user profile data
							rating.setRating((float) Double
									.parseDouble(json_user.getString("rating")));
							Button ok = (Button) dialog1.findViewById(R.id.ok);
							name.setText(json_user.getString("username"));
							email.setText(json_user.getString("email"));
							major.setText(json_user.getString("major"));
							phone.setText(json_user.getString("phone"));
							cnt.setText("Out of "
									+ json_user.getString("numRatings")
									+ " rating(s)");

							Drawable drawable;

							try {
								drawable = grabImageFromUrl(UserFunctions
										.getIp()
										+ "profilepictures/"
										+ json_user.getString("img"));
								pic.setImageDrawable(drawable);
							} catch (Exception e) {
								e.printStackTrace();
							}
							
							// Close dialog
							close.setOnClickListener(new View.OnClickListener() {

								public void onClick(View v) {
									dialog1.dismiss();
								}

							});
							
							// Message profile you are viewing
							message.setOnClickListener(new View.OnClickListener() {

								public void onClick(View v) {

									// Bundle the selected tutor for the
									// ScheduleRequestActivity (We will add to
									// the database in the next frame)
									Bundle b = new Bundle();
									b.putString("sender",
											(String) item.get("un"));
									b.putString("subject", "null");

									dialog1.dismiss();	
									
									// Goto the ScheduleRequestActivity
									Intent log = new Intent(
											getApplicationContext(),
											ReplyMessageActivity.class);
									log.putExtras(b);
									startActivity(log);
									finish();
								}
							});

							dialog1.setCanceledOnTouchOutside(true);
							dialog1.show();
						} catch (JSONException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
				});
			}
		});

	}

	// -----------------------------------------------
	// GETDATA
	// Retreives and returns list of available tutors from the database
	// -----------------------------------------------
	private List<Map<String, Object>> getData() throws Exception {

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); // Used
																				// to
																				// store
																				// the
																				// available
																				// tutors
																				// from
																				// Database

		// Retrieve tutor notifications
		UserFunctions uf = new UserFunctions();
		JSONObject json = uf.retreiveTutorNotifications(un, "1");

		// Stores size of the list returned from Database
		int size;

		try {
			size = Integer.parseInt(json.getString("size"));
			// Loop the size of the list
			for (int i = 0; i < size; i++) {
				try {

					Map<String, Object> map = new HashMap<String, Object>();

					// Each object is stored in relation to an String integer,
					// i.e "1", "2", "3", ...
					JSONObject json_not = json.getJSONObject("" + i);

					// Place each object in the HashMap
					map.put("tutoree", json_not.getString("tutoree"));
					map.put("date", json_not.getString("date"));
					map.put("sub", json_not.getString("subject"));
					map.put("time", json_not.getString("time"));
					map.put("tutor", json_not.getString("tutor"));
					map.put("type", json_not.getString("type"));
					map.put("location", json_not.getString("location"));
					map.put("other", json_not.getString("other"));
					map.put("id", json_not.getString("id"));

					list.add(map);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (NumberFormatException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		json = uf.retreiveTutorNotifications(un, "4");

		try {
			size = Integer.parseInt(json.getString("size"));

			// Loop the size of the list
			for (int i = 0; i < size; i++) {
				try {

					Map<String, Object> map = new HashMap<String, Object>();

					// Each object is stored in relation to an String integer,
					// i.e "1", "2", "3", ...
					JSONObject json_not = json.getJSONObject("" + i);

					// Place each object in the HashMap
					map.put("tutoree", json_not.getString("tutoree"));
					map.put("date", json_not.getString("date"));
					map.put("sub", json_not.getString("subject"));
					map.put("time", json_not.getString("time"));
					map.put("tutor", json_not.getString("tutor"));
					map.put("type", json_not.getString("type"));
					map.put("location", json_not.getString("location"));
					map.put("other", json_not.getString("other"));
					map.put("id", json_not.getString("id"));

					list.add(map);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (NumberFormatException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		json = uf.retreiveTutorNotifications(un, "3");

		try {
			size = Integer.parseInt(json.getString("size"));

			// Loop the size of the list
			for (int i = 0; i < size; i++) {
				try {

					Map<String, Object> map = new HashMap<String, Object>();

					// Each object is stored in relation to an String integer,
					// i.e "1", "2", "3", ...
					JSONObject json_not = json.getJSONObject("" + i);

					// Place each object in the HashMap
					map.put("tutoree", json_not.getString("tutoree"));
					map.put("date", json_not.getString("date"));
					map.put("sub", json_not.getString("subject"));
					map.put("time", json_not.getString("time"));
					map.put("tutor", json_not.getString("tutor"));
					map.put("type", json_not.getString("type"));
					map.put("location", json_not.getString("location"));
					map.put("other", json_not.getString("other"));
					map.put("id", json_not.getString("id"));

					list.add(map);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (NumberFormatException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return list;
	}

	private Drawable grabImageFromUrl(String url) throws Exception {
		return Drawable.createFromStream(
				(InputStream) new URL(url).getContent(), "src");
	}

}
